<script>
import { getPermissionListAPI } from '@/api/permissionApi'
import { assignPremAPI, findRoleDetailAPI } from '@/api/roleApi'
import { transToTreeData } from '@/utils'

export default {
  name: 'permissionList',
  props: {
    isShowPermission: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /* 权限点列表 */
      permissionList: [],
      /* 角色id */
      id: '',
      /* tree组件展示的数据字段 */
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    /* 获取权限点列表的请求函数 */
    async fetchPermission() {
      try {
        const { data } = await getPermissionListAPI()
        this.permissionList = transToTreeData(data, 0)
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    /* 获取角色详情的请求函数 */
    async fetchRoleDetail(id) {
      const { data: { permIds } } = await findRoleDetailAPI(id)
      /*
      *通过keys设置目前勾选的节点，使用此方法必须设置node-key属性
      * setCheckedKeys(keys, leafOnly)接收两个参数，1.勾选节点的key的数组 2.boolean类型的参数，若为true则仅设置叶子节点的选中状态默认值为 false
      */
      // 记录角色的id
      this.id = id
      // 设置选中的节点
      setTimeout(() => {
        this.$refs.tree.setCheckedKeys(permIds)
      }, 500)
    },
    /* 弹框关闭时的回调函数 */
    handleClose() {
      this.$emit('update:isShowPermission', false)
    },
    /* 点击确定按钮的回调函数 */
    async handleSubmit() {
      try {
        /* 整理参数 */
        const { id } = this
        const permIds = this.$refs.tree.getCheckedKeys()
        /* 调用 assignPremAPI()接口函数传入当前角色的ID和勾选的权限ID数组 */
        const { message } = await assignPremAPI({ id, permIds })
        this.$message.success(message)
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    /* 点击取消按钮的回调函数 */
    handleCancel() {
      this.$emit('update:isShowPermission', false)
    }
  },
  watch: {
    /* 监听isShowPermission字段的变化 */
    isShowPermission(newValue, oldValue) {
      if (!newValue) {
        this.$refs.tree.setCheckedKeys([])
      }
    }
  }
}
</script>

<template>
  <el-dialog title="分配权限" append-to-body :visible="isShowPermission" :close-on-click-modal="false" @close="handleClose">
    <el-tree ref="tree" :data="permissionList" :props="defaultProps" show-checkbox default-expand-all node-key="id" check-strictly></el-tree>
    <span slot="footer" class="dialog-footer">
    <el-button @click="handleCancel">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </span>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
